﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETPerformance.App_BusinessLogic.BasePages;
using ASPNETPerformance.App_BusinessLogic.Helpers;
using ASPNETPerformance.App_BusinessLogic.Utils;
using ASPNETPerformance.App_BusinessLogic.ViewState;

namespace ASPNETPerformance._01_ViewState {
    public partial class Compression : BasePage {
        protected void Page_Load( object sender, EventArgs e ) {
            if ( !this.Page.IsPostBack ) {
                BindData();
            }
        }

        private void BindData()
        {
            this.btnAlert.OnClientClick = 
                CommonHelper.GetCookieBool( "IsViewStateCompression" ) ? 
                "JAVASCRIPT:GetStateZize( false );return false;" : "JAVASCRIPT:GetStateZize( true );return false;";
        }

        protected override void SavePageStateToPersistenceMedium( object pageViewState ) {
            if ( CommonHelper.GetCookieBool( "IsViewStateCompression" ) ) {
                LosFormatter losformatter = new LosFormatter();
                StringWriter sw = new StringWriter();
                losformatter.Serialize( sw, pageViewState );
                string viewStateString = sw.ToString();
                byte[] b = Convert.FromBase64String( viewStateString );
                b = ViewStateCompression.Compress( b );
                
                // 兼容ASP.NET AJAX 的ViewState压缩
                if ( ScriptManager.GetCurrent( this ) != null )
                {
                    ScriptManager.RegisterHiddenField( this, "__ZIPSTATE", Convert.ToBase64String( b ) );
                }
                else
                {
                    ClientScript.RegisterHiddenField( "__ZIPSTATE", Convert.ToBase64String( b ) );
                }
            }
            else {
                base.SavePageStateToPersistenceMedium( pageViewState );
            }
        }

        // 序列化ViewState
        protected override object LoadPageStateFromPersistenceMedium() {
            if ( CommonHelper.GetCookieBool( "IsViewStateCompression" ) ) {
                string custState = Request.Form[ "__ZIPSTATE" ];
                byte[] b = Convert.FromBase64String( custState );
                b = ViewStateCompression.Decompress( b );
                LosFormatter losformatter = new LosFormatter();
                return losformatter.Deserialize( Convert.ToBase64String( b ) );
            }
            else {
                return base.LoadPageStateFromPersistenceMedium();
            }
        }
    }
}